import React, { useEffect, useState, memo } from 'react';
import { Card, Select, Descriptions } from 'antd';
import { useIntl } from 'umi';
import { TIMEFORMAT } from '@/utils/const';
import moment from 'moment';
import { Pie } from '@ant-design/charts';
import { getText } from '@/utils/utils';

import type { DataType } from '../../model';

import styles from './index.less';

const { Option } = Select;

const pieConfig = {
  autoFit: true,
  appendPadding: 10,
  angleField: 'number',
  colorField: 'label',
  radius: 0.8,
  label: {
    type: 'outer',
    content: '{name}',
    // content: '{name} {percentage}',
  },
  legend: false,
  interactions: [{ type: 'pie-legend-active' }, { type: 'element-active' }],
  // color: ({ label }: { label: string }) => {
  //   if (label === f({ id: 'global.unlabeld' })) {
  //     return '#ccc';
  //   }
  // },
  // color: ["#5B8FF9","#CDDDFD","#61DDAA","#CDF3E4","#65789B","#CED4DE","#F6BD16","#FCEBB9","#7262fd","#D3CEFD","#78D3F8","#D3EEF9","#9661BC","#DECFEA","#F6903D","#FFE0C7","#008685","#BBDEDE","#F08BB4","#FFE0ED"],
  height: 240,
}

export interface InfoType {
  taskId?: number;
  taskName?: string;
  annotator?: string;
  status?: string;
  startTime?: number;
  endTime?: number;
  totalNum?: number;
  annotNum?: number;
  labelProportion?: {
    label: string;
    number: number;
  }[];
}

interface VersionType {
  id: number;
  version: string;
}

interface Props {
  loading: boolean;
  info: InfoType;
  versionIds: VersionType[];
  fetchAnnotInfo: (id: string | number) => void;
  annotStatus: DataType[];
}

const AnnotInfo: React.FC<Props> = props => {
  const { formatMessage: f } = useIntl();
  const { loading, info, versionIds, fetchAnnotInfo, annotStatus } = props;

  const [curVersionId, setCurVersionId] = useState<number>(versionIds[0].id);

  const annotNum = info.annotNum || 0;
  const allNum = info.totalNum || 1;
  const unAnnotNum = allNum - (info.annotNum || 0);
  const pregressConfig = {
    data: [
      { label: f({ id: 'global.labeled' }), number: annotNum },
      { label: f({ id: 'global.unlabeld' }), number: unAnnotNum },
    ],
    innerRadius: 0.8,
    ...pieConfig,
    label: false,
    statistic: {
      title: false,
      content: false,
    },
    tooltip: {
      customContent: (title: string, data: any[]) => {
        const ratio = ((data[0]?.data.number / (info.totalNum || 1)) * 100).toFixed(2) + '%';
        const container = document.createElement('div');
        container.className = 'g2-tooltip';
        // const titleDiv = `<div class="g2-tooltip-title" style="margin-top: 12px;margin-bottom: 12px;">${title}</div>`;
        let listItem = '';
        data.forEach((item) => {
          listItem += `<li class="g2-tooltip-list-item" data-index={index} style="margin-bottom:4px;display:flex;align-items: center;">
            <span style="background-color:${item?.mappingData?.color || item?.color};" class="g2-tooltip-marker"></span>
            <span style="display:inline-flex;flex:1;justify-content:space-between">
            <span style="margin-right: 16px;">${item?.name}:</span><span>${ratio}</span>
            </span>
          </li>`;
        });
        container.innerHTML = listItem;
        return container;
      },
    }
  };

  const labelConfig = {
    data: info?.labelProportion || [],
    ...pieConfig,
  };

  useEffect(() => {
    setCurVersionId(versionIds[0].id);
  }, [versionIds]);

  useEffect(() => {
    fetchAnnotInfo(curVersionId);
  }, [curVersionId]);

  return (
    <Card
      title={(
        <div style={{ display: 'flex', alignItems: 'center' }}>
          <h1>{f({ id: 'dataSet.detail.annot' })}</h1>
          <Select
            style={{ margin: '0 16px' }}
            onChange={value => setCurVersionId(value)}
            value={curVersionId}
          >
            {versionIds.map(i => (
              <Option key={i.id} value={i.id}>{i.version}</Option>
            ))}
          </Select>
          {f({ id: 'dataSet.detail.annot.select' })}
        </div>
      )}
      loading={loading}
    >
      <div className={styles.annotInfoBox}>
        <Descriptions bordered column={1} style={{ flex: 1 }}>
          <Descriptions.Item label={f({ id: 'dataSet.detail.annot.name' })}>
            {info?.taskName || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={f({ id: 'dataSet.detail.annot.annotator' })}>
            {info?.annotator || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={f({ id: 'dataSet.detail.annot.status' })}>
            {getText(annotStatus, info?.status) || '-'}
          </Descriptions.Item>
          <Descriptions.Item label={f({ id: 'global.startTime' })}>
            {info?.startTime ? moment(info.startTime).format(TIMEFORMAT) : '-'}
          </Descriptions.Item>
          <Descriptions.Item label={f({ id: 'global.endTime' })}>
            {info?.endTime ? moment(info.endTime).format(TIMEFORMAT) : '-'}
          </Descriptions.Item>
        </Descriptions>
        <div className={styles.charts}>
          <div><Pie {...pregressConfig} /></div>
          <div>
            <div>{f({ id: 'dataSet.detail.annot.progress.title' }, { total: info.annotNum })}</div>
            <div>{f({ id: 'dataSet.detail.annot.progress.tips' })}</div>
          </div>
        </div>
        <div className={styles.charts}>
          <div><Pie {...labelConfig} /></div>
          <div>{f({ id: 'dataSet.detail.annot.label.title' })}</div>
        </div>
      </div>
    </Card>
  )
}

function arePropsEqual(prevProps: Props, nextProps: Props) {
  // 标注任务id变化时才重新渲染组件
  return prevProps.info?.taskId === nextProps.info?.taskId;
}

export default memo(AnnotInfo, arePropsEqual);